/*
 * Copyright (c) 2020-2022 Jinsp-tech. All rights reserved.
 */

package com.jinsp.networklibrary;

import com.jinsp.networklibrary.bean.TCPBaseDataBean;
import com.jinsp.networklibrary.command.ITCPCommand;

import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

/**
 * Created by luoshuai on 1/13/22
 * <p>
 * 连接会话管理类
 */
public class TCPSessionManager {

    private static volatile TCPSessionManager INSTANCE;
    private NioSocketConnector mNioSocketConnector;
    private IoSession mIoSession;
    private volatile boolean isTcpReadIdle;

    private TCPSessionManager() {
    }

    public static TCPSessionManager getInstance() {
        if (INSTANCE == null) {
            synchronized (TCPSessionManager.class) {
                if (INSTANCE == null) {
                    INSTANCE = new TCPSessionManager();
                }
            }
        }
        return INSTANCE;
    }

    /**
     * 向服务端发送数据
     *
     * @param tcpData 发送的数据
     * @param <T>     泛型
     */
    public <T> void sendData(TCPBaseDataBean<T> tcpData) {
        if (tcpData != null && mIoSession != null && !mIoSession.isClosing()) {
            mIoSession.write(tcpData);
        }
    }

    /**
     * 想服务端发送命令
     *
     * @param command 命令
     * @param <S>     服务端数据类型
     * @param <C>     客户端数据类型
     */
    public <C, S> void sendCommand(ITCPCommand<C, S> command) {
        if (command != null && mIoSession != null && !mIoSession.isClosing()) {
            mIoSession.write(command);
        }
    }

    /**
     * 释放连接资源
     */
    public void release() {
        isTcpReadIdle = false;
        if (mIoSession != null && !mIoSession.isClosing()) {
            mIoSession.closeNow();
            mIoSession = null;
        }
        if (mNioSocketConnector != null) {
            mNioSocketConnector.dispose();
            mNioSocketConnector = null;
        }
    }

    /**
     * 判断是否正在连接
     *
     * @return true -- 正在连接
     */
    public boolean isConnected() {
        return mIoSession != null && mIoSession.isConnected();
    }

    public NioSocketConnector getNioSocketConnector() {
        return mNioSocketConnector;
    }

    public void setNioSocketConnector(NioSocketConnector nioSocketConnector) {
        this.mNioSocketConnector = nioSocketConnector;
    }

    public IoSession getIoSession() {
        return mIoSession;
    }

    public void setIoSession(IoSession mIoSession) {
        this.mIoSession = mIoSession;
    }

    public boolean isTcpReadIdle() {
        return isTcpReadIdle;
    }

    public void setTcpReadIdle(boolean tcpReadIdle) {
        isTcpReadIdle = tcpReadIdle;
    }
}
